package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.OrderBean;
import com.project.bean.ShopCartBean;
import com.project.mapper.IOrderMapper;
import com.project.mapper.IShopCartMapper;
import com.project.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private IOrderMapper orderMapper;
    @Autowired
    private IShopCartMapper shopCartMapper;

    @Override
    public IPage<OrderBean> findAll(int pageNO, int userId) {
        return orderMapper.findAll(new Page<OrderBean>(pageNO,PAGE_SIZE),userId);
    }

    @Override
    public void add(OrderBean order, Integer userId) {
        order.setUserId(userId);
        orderMapper.insert(order);
        //得到该用户的购物车信息
        QueryWrapper<ShopCartBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId",userId);
        shopCartMapper.selectList(qw);
        List<ShopCartBean> shopCartBeanList = shopCartMapper.selectList(qw);

        //添加订单明细
        orderMapper.addOrderDetail(order.getId(),shopCartBeanList);
        //清空该用户的购物信息
        QueryWrapper<ShopCartBean> sqw = new QueryWrapper<>();
        sqw.eq("fk_userId",userId);
        shopCartMapper.delete(sqw);
    }

    @Override
    public OrderBean findById(int orderId) {
        OrderBean orderBean = orderMapper.selectById(orderId);
        orderBean.setList(orderMapper.findByOrder(orderId));
        return orderBean;
    }

    @Override
    public IPage<OrderBean> findByItem(int pageNO, String status, LocalDate startDate, LocalDate endDate) {
        QueryWrapper<OrderBean> qw = new QueryWrapper<>();
        if (status!=null && status.length()!=0) {
            qw.eq("o_status", status);
        }
        if (startDate!=null) {
            qw.ge("o_orderTime", startDate);
        }
        if (endDate!=null) {
            qw.le("o_orderTime", endDate);
        }
        return orderMapper.selectPage(new Page<OrderBean>(pageNO,PAGE_SIZE),qw);
    }

    @Override
    public void updateStatus(int orderId, String status) { //发货
        OrderBean orderBean = orderMapper.selectById(orderId);
        orderBean.setStatus(status);
        orderMapper.updateById(orderBean);
    }

    @Override
    public List<OrderBean> findBySend() {
        QueryWrapper<OrderBean> qw = new QueryWrapper<>();
        qw.eq("o_status","未发货");
        return orderMapper.selectList(qw);
    }
}
